/* eslint-disable react-hooks/exhaustive-deps */
import EmptyContent from '@/components/EmptyContent';
import { getOrderListInfo } from '@/service/apis/order';
import { View } from '@tarojs/components';
import Taro, { getCurrentInstance, useDidShow } from '@tarojs/taro';
import { useEffect, useState, useRef } from 'react';
import { AtTabs, AtTabsPane } from 'taro-ui';
import { getOrderStatus } from './utils';
import OrderItem from './component/OrderItem';

import './style.scss';

const OrderList = () => {
  const allList: any = useRef();
  const [current, setCurrent] = useState(0);
  const { router } = getCurrentInstance();
  const [list, setList] = useState<any>(null);
  const tabList = [
    { title: '全部', value: 0 },
    { title: '待付款', value: 1 },
    { title: '待收货', value: 2 },
    { title: '已完成', value: 3 },
  ];

  useDidShow(() => {
    init();
  });

  const init = async () => {
    const { order_status, type } = router?.params || {};
    const { data } = await getOrderListInfo({ type });
    const newList = data?.list.map((item) => {
      return {
        ...item,
        orderStatus: getOrderStatus(item.order_status),
      };
    });
    allList.current = newList;
    setList(newList);
    onTabChange(Number(order_status));
  };

  // 切换tab
  const onTabChange = (value: number) => {
    console.log('value', value);
    setCurrent(value);
    if (value === 0) {
      setList(allList.current);
      return;
    }
    const _currentList = allList.current.filter((item: any) => {
      return item.orderStatus === value;
    });
    setList(_currentList);
  };

  // 点击订单列表卡片跳转详情页
  const onHandle = (order: any) => {
    console.log('order: ', order);
    Taro.navigateTo({
      url: `/subPages/order/detail/index?orderCode=${order.order_sn}&type=${order.order_type}`,
    });
  };
  console.log('list', list);
  return (
    <View className="order-liast-container">
      <AtTabs scroll current={current} tabList={tabList} onClick={onTabChange}>
        {tabList.map((tab, index) => {
          return (
            <AtTabsPane key={tab.value} current={current} index={index}>
              <View className="product-list">
                {list &&
                  list?.map((order: any) => {
                    return (
                      <OrderItem
                        key={order.id}
                        orderInfo={order}
                        onHandle={() => onHandle(order)}
                      />
                    );
                  })}
                {list?.length === 0 && <EmptyContent />}
              </View>
            </AtTabsPane>
          );
        })}
      </AtTabs>
    </View>
  );
};
export default OrderList;
